// pages/addDizhi/addDizhi.js
import api from '../../utils/api.js'
var app = getApp();
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
import { HTTP } from '../../utils/http.js';
import { config } from '../../utils/config'
var areaTool = require('../../utils/area.js');
let http = new HTTP()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        // 此页面 页面内容距最顶部的距离
        biaoqian: ["家", "公司", "学校"],
        current: 0,
        sex: 0,
        name: "",
        phone: "",
        xxdz: "",
        status: false,
        lon: "",
        lat: "",
        animationAddressMenu: {},
        animationAddressMenu1: {},
        addressMenuIsShow: false,
        communityIsShow: false,
        value: [0, 0, 0],
        provinces: [],
        citys: [],
        areas: [],
        select: 0,
        town: "",
        num: 0, //校验是用到的
        current: 0,
        communitys: [], // 附近社区列表
        imgUrl: config.imgUrl,
        selectprovince:'',
        selectcity:'',
        selectarea:'',
        show: false
    },
    /**
     * 生命周期函数--监听页面加载
     */
    // 接口
    // 获取省的列表
    getProvince(obj) {
        http.request({
            url: api.provInce,
            data: obj,
            success: (res) => {
                // 默认联动显示湖北
                let list = res.data
                list.unshift(list.splice(16, 1)[0])
                this.setData({
                    provinces: list,
                })
            }
        })
    },
    // 获取市的列表
    getCity(obj) {
        http.request({
            url: api.city,
            data: obj,
            success: (res) => {
                this.setData({
                    citys: res.data,
                })
            }
        })
    },
    sureSelectAreaListener:function(e){
        var that = this;
        that.setData({
          show: false,
          selectprovince: e.detail.currentTarget.dataset.province,
          selectcity: e.detail.currentTarget.dataset.city,
          selectarea: e.detail.currentTarget.dataset.area
        })
      },
      chooseAddress:function(){
        console.log("xuanzedizhi")
        var that = this;
        that.setData({
          show:true
        })
      },
    // 获取县的列表
    getCounty(obj) {
        http.request({
            url: api.county,
            data: obj,
            success: (res) => {
                this.setData({
                    county: res.data,
                })
            }
        })
    },
    // 添加地址
    add_address(obj) {
        console.log('=================', obj)
        http.request({
            url: api.addAddress,
            data: obj,
            success: (res) => {
                console.log(res)
                if (res == "detail长度不能小于 5") {
                    wx.showToast({
                        title: '请填写具体的详细地址',
                        icon: "none",
                        duration: 1500
                    })
                    return false
                }
                if (res.code == 200) {
                    wx.showToast({
                        title: '添加成功',
                        duration: 1500
                    })
                    wx.setStorageSync('city_id', obj.city_id)
                    setTimeout(() => {
                        wx.navigateBack({})
                    }, 1000)
                } else if (res.code == 1003) {
                    wx.showToast({
                        title: '请不要重复提交',
                        icon: 'none',
                        duration: 1500
                    })
                }
            }
        })
    },
    selectAddress(){
        this.setData({
            show : true
        })
    },
    // 根据经纬度以及城市ID拿到用户附近的小区列表
    getUserUptowns(obj) {
        http.request({
            url: api.getUserUptown,
            data: obj,
            success: (res) => {
                console.log(res.data)
                var communitys = []
                for (var i in res.data) {
                    console.log(i, res.data[i])
                    communitys.push({ name: res.data[i], type: 0 })
                }
                communitys.push({ name: "请手动输入小区地址", type: 1 })
                this.setData({
                    communitys
                })
            }
        })
    },
    // 存储用户的小区名全国加经纬度那种
    addNationwideUptown(obj) {
        console.log('=========================', obj)
        http.request({
            url: api.addNationwideU,
            data: obj,
            success: (res) => {}
        })
    },

    // 事件
    // 输入姓名
    name(e) {
        this.setData({
            name: e.detail.value
        })
    },
    // 更改性别
    changeSex(e) {
        console.log(e.target.dataset.sex)
        this.setData({
            sex: e.target.dataset.sex
        })
    },
    // 输入手机号
    phone(e) {
        this.setData({
            phone: e.detail.value
        })
    },
    // 输入详细地址
    xxdz(e) {
        var xxdz = e.detail.value
        this.setData({
            xxdz
        })
    },
    // 输入社区名称
    write(e) {
        var community = this.data.community
        community.name = e.detail.value
        this.setData({
            community
        })
    },
    // 更改标签
    changeIndex(e) {
        this.setData({
            current: e.target.dataset.idx
        })
    },
    // 三级联动
    // 点击所在地区弹出选择框
    select: function(e) {
        //  如果已经显示，不在执行显示动画
        if (this.data.addressMenuIsShow) {
            return false
        } else {
            //  执行显示动画
            this.startAddressAnimation(true)
        }
    },
    select1(e) {
        if (!this.data.areaInfo) {
            wx.showToast({
                title: '请先选择地区！',
                icon: "none",
            })
            return false
        }
        this.getUserUptowns({ lon: this.data.address.longitude, lat: this.data.address.latitude, city_id: this.data.city_id })
        if (this.data.communityIsShow) {
            return false
        } else {
            // 执行显示动画
            this.startAddressAnimation1(true)
        }
    },
    // 搜索地址
    choose() {
        wx.navigateTo({
            url: "/pages/getDizhi/getDizhi?order=0",
        })
    },
    // 保存
    save(e) {
        // if (this.data.community.name == "请手动输入小区地址" && this.data.community.type == 1) {
        //     wx.showToast({
        //         title: '请输入您的社区名称',
        //         icon: "none"
        //     })
        //     return false
        // }
        this.check()
        var city = this.data.city
        var value = this.data.value
        // if (this.data.num == 4) {
            let obj = {
                name: this.data.name,
                user_id: wx.getStorageSync("user_id"),
                sex: this.data.sex,
                mobile: this.data.phone,
                detail: this.data.xxdz,
                address: this.data.selectprovince + this.data.selectcity + this.data.selectarea,
                province:this.data.selectprovince,
                city:this.data.selectcity,
                district: this.data.selectarea,
                type: this.data.current,
                default: 1,
                hometown_procince_id: this.data.provinces[value[0]].province_id,
                hometown_city_id: this.data.citys[value[1]].city_id,
                hometown: this.data.town,
                city_id: wx.getStorageSync("city_id")
            }
            let obj2 = {
                id: wx.getStorageSync("user_id"),
                lon: '000000',
                lat: '000000',
                city_id: wx.getStorageSync("city_id"),
            }
            // this.addNationwideUptown(obj2)
            this.add_address(obj)

        // }
    },
    // 保存前的一些校验
    check() {
        var num = 0;
        if (this.data.town) {
            num++
        } else {
            wx.showToast({
                title: '请完善您的信息(家乡)',
                icon: 'none',
                duration: 1500
            })
            return ;
        }
        if (this.data.xxdz) {
          if (this.data.xxdz.length >= 5) {
            num++
          } else {
            wx.showToast({
              title: "详细地址过短",
              icon: "none",
              duration: 1500
            })
            return ;
          }
        } else {
          wx.showToast({
            title: '请完善您的信息(详细地址)',
            icon: 'none',
            duration: 1500
          })
          return ;
        }
        if(!this.data.selectprovince || !this.data.selectcity || !this.data.selectarea){
            wx.showToast({
                title: '请选择完整的地区',
                icon: 'none',
                duration: 1500
              })
              return ;
        }else{
            num++
        }

        if (this.data.phone) {
            if (!(/^1[3456789]\d{9}$/.test(this.data.phone))) {
                wx.showToast({
                    title: '手机号码有误，请重新填写',
                    icon: 'none',
                    duration: 1500
                })
                return ;
            } else {
                num++
            }
        } else {
            wx.showToast({
                title: '请完善您的信息(手机号)',
                icon: 'none',
                duration: 1500
            })
            return ;
        }
        if (this.data.name) {
            if (this.data.name.length <= 10) {
                num++
            } else {
                wx.showToast({
                    title: "请输入真实姓名",
                    icon: "none",
                    duration: 1500
                })
                return ;
            }
        } else {
            wx.showToast({
                title: '请完善您的信息(姓名)',
                icon: 'none',
                duration: 1500
            })
            return ;
        }
        this.setData({
            num
        })
    },
    //  执行动画
    startAddressAnimation(isShow) {
        if (isShow) {
            //  vh是用来表示尺寸的单位，高度全屏是100vh
            this.animation.translateY(0 + 'vh').step()
        } else {
            this.animation.translateY(40 + 'vh').step()
        }
        this.setData({
            animationAddressMenu: this.animation.export(),
            addressMenuIsShow: isShow,
        })
    },
    startAddressAnimation1(isShow) {
        console.log(isShow)
        if (isShow) {
            //  vh是用来表示尺寸的单位，高度全屏是100vh
            this.animation.translateY(0 + 'vh').step()
        } else {
            this.animation.translateY(40 + 'vh').step()
        }
        this.setData({
            animationAddressMenu1: this.animation.export(),
            communityIsShow: isShow,
        })

    },
    //  点击地区选择取消按钮
    cityCancel: function(e) {
        this.startAddressAnimation(false)
    },
    communityCancel(e) {
        this.startAddressAnimation1(false)
    },
    //  点击地区选择确定按钮
    citySure: function(e) {
        var that = this
        var city = that.data.city
        var value = that.data.value
        var city = that.data.city
        var value = that.data.value
        this.startAddressAnimation(false)
            // 将选择的城市信息显示到输入框
        var town = ""
        var city = that.data.citys[value[1]].city_name
        if (city.indexOf("市辖") != -1) {
            town = that.data.provinces[value[0]].province_name
        } else {
            town = that.data.provinces[value[0]].province_name + city
        }
        that.setData({
            town
        })
    },
    communitySure(e) {
        this.startAddressAnimation1(false)
        this.setData({
            community: this.data.communitys[this.data.current]
        })
    },
    // 处理省市县联动逻辑
    cityChange: function(e) {
        var value = e.detail.value
        var provinces = this.data.provinces
        var citys = this.data.citys
        var areas = this.data.areas
        var provinceNum = value[0]
        var cityNum = value[1]
        var countyNum = value[2]
            // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
        if (this.data.value[0] != provinceNum) {
            var id = provinces[provinceNum].province_id
            http.request({
                url: api.city,
                data: {
                    province_id: id
                },
                success: (res) => {
                    this.setData({
                        value: [provinceNum, 0, 0],
                        citys: res.data
                    })
                    var id = res.data[0]
                    http.request({
                        url: api.county,
                        data: {
                            city_id: res.data[0].city_id
                        },
                        success: (res) => {
                            this.setData({
                                areas: res.data
                            })
                        }
                    })
                }
            })
        } else if (this.data.value[1] != cityNum) {
            // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
            var id = citys[cityNum].city_id
            http.request({
                url: api.county,
                data: {
                    city_id: id
                },
                method: "POSt",
                success: (res) => {
                    this.setData({
                        value: [provinceNum, cityNum, 0],
                        areas: res.data
                    })
                }
            })
        } else {
            // 滑动选择了区
            this.setData({
                value: [provinceNum, cityNum, countyNum]
            })
        }
    },

    communityChange(e) {
        this.setData({
            current: e.detail.value[0]
        })
    },


    onLoad: function(options) {
        this.getProvince()
        this.getCity({ province_id: 420 })
        this.getCounty({ city_id: 110100000000 })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        var address = this.data.address || []
        if (address.length != 0) {
            this.setData({
                has: 1,
                address : wx.getStorageSync('integralAddress')
            })
        } else {
            this.setData({
                has: 0
            })
        }
        var animation = wx.createAnimation({
            duration: 1500,
            timingFunction: 'linear',
        })
        this.animation = animation
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

       

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    }
})